﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;

namespace T.FAS.Runtime.DataAccess.SQLDom
{
    /// <summary>
    /// From类
    /// </summary>
    /// <remarks>SQL语句中的From</remarks>
    [Serializable]
    public class From : SqlElement
    {      

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        public From()
            : base()
        {
            base.CreateChildCollection();
        }

        #endregion

        #region 属性

        //包裹列名的方法
        public Func<string, string> FieldNameWraps { get; set; }
        #endregion

        #region 方法

        /// <summary>
        /// 转换成SQL
        /// </summary>
        /// <returns>SQL</returns>
        public override string ToSQL()
        {
            var fromList = new List<string>();
            for (int index = 0; index < this.ChildCollection.Count; index++)
            {
                var sqlele = this.ChildCollection[index];
                if(sqlele is SqlTable sqlTable)
                {
                    if (FieldNameWraps != null)
                        sqlTable.FieldNameWraps = FieldNameWraps;
                }
                else if(sqlele is FromItem fromItem)
                {
                    if (FieldNameWraps != null)
                        fromItem.FieldNameWraps = FieldNameWraps;
                }
                var from = sqlele.ToSQL();
                if (!string.IsNullOrWhiteSpace(from))
                    fromList.Add(from);
            }

            return string.Join(",", fromList);
        }

        #endregion

    }
}